-module(error_logs).
-export([start_error_log/1, end_error_log/1, error_log/3, error_log/2]).

start_error_log(Name) ->
	FPid = self(),
	Pid = spawn(fun() -> error_log_loop(Name, FPid) end),
	receive
		error_log_ok ->
			{errlog, Pid};
		{error_log_error, Reason} ->
			{errlog_error, Reason}
	end.

end_error_log({errlog, Pid}) ->
	Pid ! logend.

print_datetime(IoDevice) ->
	{{Year, Month, Day}, {Hour, Minute, Second}} = calendar:local_time(),
	io:format(IoDevice, "~p/~p/~p ~p:~p:~p ", [Year, Month, Day, Hour, Minute, Second]).

error_log_loop(IoDevice) ->
	receive
		{logmsg, Format, ColMsg} ->
			print_datetime(IoDevice),
			io:format(IoDevice, Format, ColMsg),
			error_log_loop(IoDevice);
		{logmsg, Message} ->
			print_datetime(IoDevice),
			io:format(IoDevice, Message, []),
			error_log_loop(IoDevice);
		logend ->
			file:close(IoDevice);
		Other ->
			{{Year, Month, Day}, {Hour, Minute, Second}} = calendar:local_time(),
			io:format("~p/~p/~p ~p:~p:~p unknown error_log command(~p).~n", [Year, Month, Day, Hour, Minute, Second, Other]),
			error_log_loop(IoDevice)
	end.
error_log_loop(Name, FPid) ->
	case file:open(Name, [write, append, binary]) of
		{ok, IoDevice} ->
			FPid ! error_log_ok,
			error_log_loop(IoDevice);
		{error, Reason} ->
			FPid ! {errlog_error, Reason}
	end.
	

error_log({errlog, Pid}, Format, ColMsg) ->
	Pid ! {logmsg, Format, ColMsg}.

error_log({errlog, Pid}, Message) ->
	Pid ! {logmsg, Message}.

